package com.itheima.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.common.CustomException;
import com.itheima.entity.Category;
import com.itheima.entity.Dish;
import com.itheima.entity.Setmeal;
import com.itheima.mapper.CategoryMapper;
import com.itheima.service.CategoryService;
import com.itheima.service.DishService;
import com.itheima.service.SetmealService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;

@Service
@Slf4j
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {

    @Autowired
    private DishService dishService;
    @Autowired
    private SetmealService setmealService;

    @Override
    public boolean deleteById(Long id) {
        QueryWrapper<Dish> dishQueryWrapper = new QueryWrapper<>();
        dishQueryWrapper.select("count(*) as count");
        dishQueryWrapper.eq("category_id",id);
        Map<String,Object> dishServeletMap = dishService.getMap(dishQueryWrapper);
        Long dishcount = (Long) dishServeletMap.get("count");
        log.info("根据categoryId去菜品表查询,查到的套餐数量为：{}",dishcount);
        if (dishcount > 0){
            log.info("此分类有菜品");
            throw new CustomException("当前分类下关联了菜品，不能删除");
        }
        QueryWrapper<Setmeal> SetmealQueryMapper = new QueryWrapper<>();
        SetmealQueryMapper.select("count(*) as count");
        SetmealQueryMapper.eq("category_id",id);
        Map<String,Object> setmealServeletMap = setmealService.getMap(SetmealQueryMapper);
        Long setmealcount = (Long) setmealServeletMap.get("count");
        log.info("根据categoryId去套餐表查询,查到的套餐数量为：{}",setmealcount);
        if (setmealcount > 0){
            log.info("此分类有套餐");
            throw new CustomException("当前分类下关联了菜品，不能删除");
        }
        super.removeById(id);
        return true;
    }
}
